package com.shiguiwu.springboot3.controller;

import cn.hutool.core.lang.TypeReference;
import cn.hutool.json.JSONUtil;
import com.shiguiwu.springboot3.dto.UserDTO;
import com.shiguiwu.springboot3.service.UserService;
import com.shiguiwu.springboot3.util.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @description: user控制器
 * @author: stone
 * @date: Created by 2023/7/2 20:51
 * @version: 1.0.0
 * @pakeage: com.shiguiwu.springboot3.controller
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;


    @GetMapping("/test")
    public R<Integer> test() {
        return R.ok(userService.test());
    }

    @GetMapping("/test2")
    public R<Integer> test2() {
        if (1 == 1) throw new RuntimeException("你好啊！！");
        return R.ok(1);
    }

    @GetMapping(value = "/test3", produces = {MediaType.TEXT_HTML_VALUE})
    public String test3() {
        return JSONUtil.toJsonStr(R.ok(userService.testBatch()));
    }

    @GetMapping(value = "/test4", produces = {MediaType.TEXT_HTML_VALUE})
    public String test4() {
        UserDTO userDTO = new UserDTO();
        userDTO.setId(1);
        userDTO.setUsername("111");
        return JSONUtil.toJsonStr(R.ok(userDTO));
    }


    @GetMapping(value = "/test5")
    public R<UserDTO> test5() {
        UserDTO userDTO = new UserDTO();
        userDTO.setId(1);
        userDTO.setUsername("111");
        return R.ok(userDTO);
    }

    @GetMapping(value = "/timeout")
    public R<UserDTO> timeout(long time) throws InterruptedException {
        UserDTO userDTO = new UserDTO();
        userDTO.setId(1);
        userDTO.setUsername("111");
        TimeUnit.SECONDS.sleep(time);
        return R.ok(userDTO);
    }

    @GetMapping(value = "/ex")
    public R<Integer> ex(long time) throws InterruptedException {
        if (time == 0) {
            throw new RuntimeException("出异常了");
        }
        return R.ok(1);
    }

    public static void main(String[] args) {
        UserDTO userDTO = new UserDTO();
        userDTO.setId(1);
        userDTO.setUsername("111");
        List<UserDTO> list = new ArrayList<>();
        list.add(userDTO);
        String toJsonStr = JSONUtil.toJsonStr(R.ok(list));


        R<List<UserDTO>> r = JSONUtil.toBean(toJsonStr, new TypeReference<>() {

        }, true);

        log.error("json ===> {}", r);
    }
}
